//
//  HEConsulReportViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/23.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEConsulReportViewController.h"
#import "HECosulReportModel.h"
#import "HEDieaseItemCell.h"
#import "HEConsulDetailTipsCell.h"
#import "HEFindDoctorViewController.h"
#import "HEDoctorInfoModel.h"
#import "HEIMChatViewController.h"

@interface HEConsulReportViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) HECosulReportModel *details;
@property (nonatomic, assign) BOOL isHasPrivate;
@property (nonatomic, strong) HEDoctorInfoModel *docInfo;

@end

@implementation HEConsulReportViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
  
}
 
- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"咨询报告";
 
    [self.view addSubview:self.tableView];
    
    [self tableFooter];
    [self loadData];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    return _tableView;
}

- (void)initCell {
    
    _sections = @[].mutableCopy;
    _dataSource = @[].mutableCopy;

    NSMutableArray *classArr = [NSMutableArray array];
    
    NSArray *titles = @[@"咨询内容：", @"科学依据：", @"相关描述：", @"饮食注意："];

    self.formModel.dataSource = self.details.tipsArr;
    
    //
    GDFiterCellModel *textModel = [GDFiterCellModel new];
    textModel.cellKlass = HEDieaseItemCell.class;
    textModel.cellType = 1;
    
    //
    GDFiterCellModel *tipModel = [GDFiterCellModel new];
    tipModel.cellKlass = HEConsulDetailTipsCell.class;

    GDFiterCellModel *consulModel = [GDFiterCellModel new];
    consulModel.cellKlass = HEDieaseItemCell.class;
    consulModel.cellType = 3;

    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[textModel, tipModel, consulModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    int i = 0;
    for (GDFiterCellModel *model in classArr) {
        
        NSMutableArray *sec = @[].mutableCopy;
        if (model.cellType == 1) {
         
            for (NSString *str in titles) {
                GDFiterCellModel *model = [GDFiterCellModel new];
                model.cellKlass = HEDieaseItemCell.class;
                model.leftTitle = str;
                model.leftTitleColor = CNavBgColor;
                model.contentColor = CNavLightBlackColor;
                [sec addObject:model];
            }
            
            GDFormModel *fmodel = [[GDFormModel alloc] init];
            fmodel.proxyVC = self;
            fmodel.ai_content = @[IsNotNull(_details.report_name), @"依据您的回答，根据相关医学书籍，结合数据分析，给出该评估报告。 >>>查看文献", IsNotNull(_details.desc), IsNotNull(_details.ys) ];
            [_dataSource addObject:fmodel];

            self.formModel.ai_content = @[IsNotNull(_details.report_name), IsNotNull(_details.desc), IsNotNull(_details.ys) ];
        }
        else if(model.cellType == 3) {
            
            for (NSString *str in _details.questionArr) {
                GDFiterCellModel *model = [GDFiterCellModel new];
                model.cellKlass = HEDieaseItemCell.class;
                model.leftTitle = str;
                model.leftTitleColor = CNavLightBlackColor;
                model.contentColor = CNavDargGrayColor;
                [sec addObject:model];
            }
            
            GDFormModel *fmodel = [[GDFormModel alloc] init];
            fmodel.proxyVC = self;
            fmodel.ai_content = _details.answerArr;
            [_dataSource addObject:fmodel];
        }
        else {
            [_dataSource addObject: _formModel];
            [sec addObject: model];
        }
        
        [_sections addObject:sec];
        i++;
    }
     
     
    [self.tableView reloadData];
}
- (void)loadData {
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:Kask_report_detail parameters: @{@"inst_id": _inst_id} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        
        self.details = [HECosulReportModel mj_objectWithKeyValues: response.data];
 
        [self loadUserPrivateData];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)tableFooter {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 150)];
    
    // 登录按钮
    
    QMUIFillButton *consulBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    consulBtn.titleLabel.font = DYBlodFont(15);
    [consulBtn setBackgroundColor:CNavBgColor];
    [consulBtn setTitle:@"咨询医生" forState:UIControlStateNormal];
    [view addSubview:consulBtn];
    [consulBtn addTarget:self action:@selector(consulBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [consulBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).mas_offset(30);
        make.left.equalTo(view).mas_offset(50);
        make.right.equalTo(view).mas_offset(-50);
        make.height.mas_offset(40);
    }];
    
    if (!_hideConsulBtn) {
        _tableView.tableFooterView = view;
    }
}

- (void)consulBtnClick {
    
    if (self.isHasPrivate) {
        HEIMKitInfo *doc = [HEIMKitInfo new];
        doc.infoId = _docInfo.user_id;
        doc.showName = _docInfo.realname;
        doc.avatarUrlString = _docInfo.avatar;
        doc.avatarImage = IMAGE_NAMED(@"hmang");
        
        UserInfo *user = [[UserManager sharedUserManager] getUserInfo];
        HEIMKitInfo *owner = [HEIMKitInfo new];
        owner.infoId = user.id;
        owner.showName = user.realname;
        owner.avatarUrlString = user.avatar;
        owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
        
        [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];
        
        HEIMChatViewController *imVC = [HEIMChatViewController new];
        imVC.docId = _docInfo.user_id;
        [self.navigationController pushViewController:imVC animated:YES];
    }else { 
        [WOAlert alertShowTitle:@"温馨提示" message:@"您还没有签约医生，是否前往找医生？" cancelButtonTitle:@"不用了" otherButtonTitles:@"是" block:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                HEFindDoctorViewController *vc = [HEFindDoctorViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
    }
}

- (void)loadUserPrivateData {
 
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KprivateDocinfo parameters:@{} success:^(id  _Nonnull responseObject) {
        [self initCell];
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.success && response.data != nil) {
            self.isHasPrivate = YES;
            self.docInfo = [HEDoctorInfoModel mj_objectWithKeyValues: response.data];
        }
     } failure:^(NSError * _Nonnull error) {
     }];
}

 

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    GDFormModel *formModel = _dataSource[indexPath.section];

    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    GDFormModel *formModel = _dataSource[indexPath.section];

    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
      [cell refreshContent:fiterModel formModel: formModel indexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GDFormModel *formModel = _dataSource[indexPath.section];
    NSString *content = formModel.ai_content[indexPath.row];
    if ([content containsString:@"查看文献"]) {
        NSURL * file = [NSURL URLWithString: @"https://www.honglutec.com/agreement/references.html"];
        RootWebViewController *webView = [[RootWebViewController alloc] initWithUrl:file.absoluteString];
        webView.isShowCloseBtn = YES;
        webView.showPageTitle = YES;
        [self.navigationController pushViewController:webView animated:YES];
    }
}


@end
